package com.admin.service.impl;

import com.admin.entity.Admin;
import com.admin.entity.Station;
import com.admin.entity.StationRecharge;
import com.admin.mapper.AdminMapper;
import com.admin.service.IAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bean.ResponseBean;
import com.token.JwtUtil;
import com.util.IPUtil;
import com.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 管理员模块业务层
 *
 * @author marisheng
 * @since 2019-11-21
 */
@SuppressWarnings("ALL")
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;
    //实例化redis模板
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据账号和密码查数据库
     *
     * @param username
     * @param password
     * @return
     */
    public Admin login(String username, String password) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_phone", username);
        String pwd = PasswordUtil.jiami(password);
        queryWrapper.eq("admin_password", pwd);
        Admin admin = adminMapper.selectOne(queryWrapper);
        return admin;
    }

    @Override
    public List<Admin> selctyuanpassword(String adminName) {
        return adminMapper.selctyuanpassword(adminName);
    }

    @Override
    public int xiuPassword(String password , String adminName) {
        String pwd = PasswordUtil.jiami(password);
        return adminMapper.updatapasswordbyadminName(pwd , adminName);
    }


    /**
     * 得到当前系统时间
     * @return
     */
    public String NowString(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        return df.format(new Date());
    }

    /**
     * 判断验证码是否为空或错误和判断是否有这一个用户
     *
     * @param response
     * @param token
     * @param username
     * @param password
     * @param code
     * @return
     */
    @Override
    public ResponseBean tologin(HttpServletRequest request, HttpServletResponse response, String username, String password) {
        //获取ip
        String ip = IPUtil.getIpAddr(request);
        //从redis里取登录失败次数
        BoundValueOperations b = redisTemplate.boundValueOps(ip);
        if ("-1".equals(b.get())) {
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }
        //查数据是否有这个用户
        Admin admin = login(username, password);
        if (admin != null) {
            updataNowString(NowString() ,admin.getAdminId());
            b.set("0");
            String token = JwtUtil.generToken(admin.getAdminPhone(), null, null);
            //响应头也存在跨域
            response.addHeader("Access-Control-Expose-Headers", "token");
            //发送给客户端
            response.addHeader("token", token);
            return new ResponseBean(200, "success", admin);
        }

        if (!redisTemplate.hasKey(ip)) {
            b.set("1");
            b.expire(60, TimeUnit.SECONDS);
            //登录失败次数小于十，次数加一
        } else if (Integer.parseInt(b.get().toString()) < 10) {
            int tmp = Integer.parseInt(b.get().toString());
            b.set(String.valueOf(++tmp));
            b.expire(60, TimeUnit.SECONDS);
            //大于十，参数为-1,并一分钟内禁止登录
        } else {
            b.set("-1");
            b.expire(60, TimeUnit.SECONDS);
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }
        return new ResponseBean(500, "用户名或密码错误", null);

    }


    /**
     * 查找用户的沃币并且修改
     *
     * @param sr
     * @return
     */
    @Override
    public int editMoney(StationRecharge sr) {
        Admin admin = adminMapper.selectById(sr.getStationRechargeAdmin());
        if (admin.getAdminMoney() == null) {
            admin.setAdminMoney(0);
        }
        if (sr.getStationRechargeSum() > admin.getAdminMoney()) {
            return -1;
        }
        admin.setAdminMoney(admin.getAdminMoney() - sr.getStationRechargeSum());
        return adminMapper.updateById(admin);
    }


    @Autowired
    private AdminMapper AdminMapper;

    /**
     * 新增子用户
     *
     * @return
     */

    public int adduser(Admin admin) {

        if (admin.getAdminType() != null && admin.getAdminType() != "") {
            String type = admin.getAdminType().equals("0") ? "个人" : "企业";
            admin.setAdminType(type);
        }
        if (admin.getAdminPassword() != null && admin.getAdminPassword() != "") {
            String password = PasswordUtil.jiami(admin.getAdminPassword());
            admin.setAdminPassword(password);
        }
        return adminMapper.adduser(admin);
    }

    /**
     * 查询所有用户
     */
    public List findAll() {
        return adminMapper.selectList(null);
    }
    /**
     * 树的查询
     *
     * @return
     */
    public List selshangjiuser(int admin_id) {
        return adminMapper.selshangjiuser(admin_id);
    }

    @Override
    public Admin queryAdminParent(int admin_id) {
        return adminMapper.queryAdminParent(admin_id);
    }

    /**
     * 用户管理的查询
     *
     * @param page
     * @param limit
     * @param m
     * @return
     */
    @Override
    public IPage searchyhgl(int page, int limit, Map m) {
        Page p = new Page(page, limit);
        IPage result = adminMapper.searchadminWithrole(p, m);
        return result;
    }

    /**
     * 详情编辑修改(根据id修改)
     *
     * @param admin
     * @return
     */
    @Override
    public int updatebyadmin(Admin admin) {
        String type = admin.getAdminType();
        admin.setAdminType(type.equals("0")?"个人":"企业");
        return adminMapper.updateById(admin);
    }

    /**
     * 获取当前用户的可用沃币数
     *
     * @param username 用户名
     * @return 沃币数
     */
    @Override
    public int getMoney(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper();
        queryWrapper.eq("admin_phone", username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        if (admin != null) {
            return admin.getAdminMoney();
        }
        return 0;
    }


    /**
     * 删除站点时修改用户的沃币数
     *
     * @return
     */
    @Override
    public int updateAdminCoin(Station station) {
        Admin admin = adminMapper.selectById(station.getStationAdminId());
        if (admin.getAdminMoney() == null) {
            admin.setAdminMoney(0);
        }
        if (station.getStationMaximumNumberOfTerminals() == null) {
            station.setStationMaximumNumberOfTerminals(0);
        }
        admin.setAdminMoney(admin.getAdminMoney() + station.getStationMaximumNumberOfTerminals());
        return adminMapper.updateById(admin);
    }

    /**
     * 得到界面上传过来的终端数改变总的沃币数
     *
     * @param s
     * @return
     */
    @Override
    public int updataAdminmoney(Station s) {
        Admin admin = adminMapper.selectById(s.getStationAdminId());
        if (admin.getAdminMoney() == null) {
            admin.setAdminMoney(0);
        }
        if (s.getStationMaximumNumberOfTerminals() > admin.getAdminMoney()) {
            return -1;
        }
        admin.setAdminMoney(admin.getAdminMoney() - s.getStationMaximumNumberOfTerminals());
        return adminMapper.updateById(admin);
    }

    @Override
    public Admin SelectAdminByid(int id) {
        Admin admin = adminMapper.selectById(id);
        return admin;
    }

    @Override
    public boolean seladminName(String adminName) {
        Admin admin = adminMapper.seladminName(adminName);
        if (admin != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List updateselct(Map m) {
        List updateselct = adminMapper.updateselct(m);
        return updateselct;
    }

    @Override
    public int updataNowString(String nowString, int adminId) {
        return adminMapper.updataNowString(nowString ,adminId);
    }

    /**
     * 根据用户名查找用户对象
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        QueryWrapper q = new QueryWrapper();
        q.eq("admin_phone",username);
        return adminMapper.selectOne(q);
    }

    @Override
    public Admin chaUser(int admin_id){
        return adminMapper.selectById(admin_id);
    }

    /**
     * 根据用户名查询 用户id
     * @return
     */
    public Integer queryAdmin(String userInfo){

        QueryWrapper queryWrapper=new QueryWrapper();

        if(userInfo!=null && userInfo!=""){
            queryWrapper.eq("admin_phone",userInfo);
        }

        Admin admin = adminMapper.selectOne(queryWrapper);

        return admin.getAdminId();
    }

    /**
     * 进行编辑删除等操作时判断该用户是否有权限
     * updateid:表示修改的那条数据的用户id， adminid表示登录的当前用户
     * @return
     */
    @Override
    public int selectQuanxian(int updateid, String adminid){

        String admin=JwtUtil.getUsername(adminid);

        System.out.println(admin);

        Integer id = queryAdmin(admin);

//        int id=Integer.parseInt(JwtUtil.getUsername(adminid));

        String str=adminMapper.getAllChildUser(id);

        List<String> list= Arrays.asList(str.split(","));

        for(String a:list){
            if((updateid+"").equals(a)){
                return 200;
            }
        }

        return 500;
    }

    /**
     * 根据站点ID 查询 所属用户
     * @return
     */
    @Override
    public Integer selectAdminId(Integer station_id) {

        Integer integer = adminMapper.queryAdminId(station_id);

        return integer;
    }

    @Override
    public List<String> getPermissionByUsername(String username) {
        return adminMapper.getPermissionByUsername(username);
    }
}
